<template>
  <div class="register-container">
    <h2>注册</h2>
    <input v-model="username" placeholder="用户名" />
    <input v-model="password" type="password" placeholder="密码" />
    <button @click="handleRegister">注册</button>
    <div v-if="errorMessage" style="color: red; margin-top: 10px;">
      <p>{{ errorMessage }}</p>
      <p v-if="showNetworkDiagnostics" style="font-size: 12px; margin-top: 5px;">网络诊断建议:
        <ul style="text-align: left; margin-top: 5px;">
          <li>1. 确认后端服务已启动且运行在 http://localhost:9090</li>
          <li>2. 检查防火墙是否阻止端口 9090 连接</li>
          <li>3. 尝试直接访问 <a href="http://localhost:9090/api/users/register" target="_blank">http://localhost:9090/api/users/register</a> 验证服务可用性</li>
        </ul>
      </p>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import api from '@/api'

const username = ref('')
const password = ref('')
const router = useRouter()
const errorMessage = ref('')
const showNetworkDiagnostics = ref(true)

const handleRegister = async () => {
  try {
    await api.post('/api/users/register', {
      username: username.value,
      password: password.value
    })
    router.push('/login')
  } catch (error) {
    // 增强错误信息处理
    const status = error.response?.status || '未知'
    const errorDetails = error.response?.data?.message || error.message || '未知错误'
    errorMessage.value = `注册失败: ${status} - ${errorDetails}`
    console.error('注册错误详情:', error)
  }
}
</script>

<style scoped>
.register-container {
  max-width: 300px;
  margin: 100px auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
  text-align: center;
}

.register-container input {
  width: 100%;
  margin-bottom: 10px;
  padding: 8px;
}

.register-container button {
  width: 100%;
  padding: 10px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}
</style>